package com.alibaba.it.asset.codegen.db2entity.processor;

import com.alibaba.it.asset.codegen.db2entity.GenerateContext;
import com.alibaba.it.asset.codegen.db2entity.GenerateProcessor;
import com.alibaba.it.asset.codegen.db2entity.PropertyUtil;
import com.alibaba.it.asset.codegen.db2entity.vo.DBColumnVO;
import com.alibaba.it.asset.velocity.VelocityUtil;
import com.google.common.collect.Maps;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 从表格生成实体
 */
public class ServiceGenerater extends GenerateProcessorAbstract implements GenerateProcessor {

    /**
     * 生成一个实体
     *
     * @param tableName 表格名称
     * @param columns   表格的所拥有的列
     * @throws IOException
     */
    @Override
    public void process(GenerateContext genContext, String tableName, String entityName, List<DBColumnVO> columns) throws IOException {
        Map<String, Object> params = Maps.newHashMap();
        params.put("repositoryPackage", genContext.getRepositoryPackage());
        params.put("servicePackage", genContext.getServicePackage());
        params.put("entityPackage", genContext.getEntityPackage());
        params.put("EntityName", entityName);
        List<DBColumnVO> primarys = getPrimaryKey(columns);
        params.put("PrimayKeys", primarys);
        String path = genContext.getGenPath();
        String generatePath = path.replaceAll("\\\\", "/") + "/src/main/java/" + genContext.getServicePackage().replaceAll("\\.", "/") + "/" + entityName + "Service.java";
        if (isCanCreate(generatePath, genContext.getOverwrite())) {
            VelocityUtil.vmToFile(VelocityUtil.getVelocityContext(params), TPL_PATH.concat("/Service.vm"), generatePath);
        }

        generatePath = path.replaceAll("\\\\", "/") + "/src/main/java/" + genContext.getServicePackage().replaceAll("\\.", "/") + "/impl/" + entityName + "ServiceImpl.java";
        if (isCanCreate(generatePath, genContext.getOverwrite())) {
            VelocityUtil.vmToFile(VelocityUtil.getVelocityContext(params), TPL_PATH.concat("/ServiceImpl.vm"), generatePath);
        }
    }
}